<template>
	<view class="studio">
		<view class="levelOne level">
			<view class="item">
				<view class="label">工作室头像</view>
				<view class="value" @click="editAvatar">
					<view class="valueText">
						<img :src="detailInfo.avatar" alt="" class="pic" />
					</view>
					<uni-icons type="right" size="16"></uni-icons>
				</view>
			</view>
			<view class="item">
				<view class="label">工作室名称</view>
				<view class="value" @click="toUrl('name')">
					<view class="valueText">{{ detailInfo.name }}</view>
					<uni-icons type="right" size="16"></uni-icons>
				</view>
			</view>
			<view class="item">
				<view class="label">工作室电话</view>
				<view class="value" @click="toUrl('phone')">
					<view class="valueText">{{ detailInfo.phone }}</view>
					<uni-icons type="right" size="16"></uni-icons>
				</view>
			</view>
			<view class="title">
				<view class="item">
					<view class="label">工作室介绍</view>
					<view class="value" @click="toUrl('introduce')">
						<uni-icons type="right" size="16"></uni-icons>
					</view>
				</view>
				<view class="text">{{ detailInfo.introduce }}</view>
			</view>
			<view class="title">
				<view class="item">
					<view class="label">接单地址</view>
					<!-- <view class="value" @click="toUrl('address')">
						<uni-icons type="right" size="16"></uni-icons>
					</view> -->
				</view>
				<view class="text">{{ detailInfo.province }}{{ detailInfo.city }}{{ detailInfo.area }}{{ detailInfo.address }}</view>
			</view>
		</view>
		<view class="default_income_box" @click="toIncomeSetUp()">
			<view class="default_income_title">
				<view class="">工作室默认收入分成占比</view>
				<uni-icons type="right" size="16" color="#808080"></uni-icons>
			</view>
			<view class="default_income_block">
				<view class="income_block">
					<view class="income_name">线上商城</view>
					<!--					<view class="income_self">本人：{{ getSelfIncome(incomeSetUpInfo.mallPromotionRatio) }}%</view>-->
					<view class="income_promoter">推广收入：{{ incomeSetUpInfo.memberMallPromotionRatio }}%</view>
				</view>
				<view class="income_block bg_c_F1EEFF">
					<view class="income_name">服务订单</view>
					<!--					<view class="income_self">本人：{{ getSelfIncome(incomeSetUpInfo.serviceAcceptanceRatio) }}%</view>-->
					<view class="income_promoter">接单收入：{{ incomeSetUpInfo.memberServiceAcceptanceRatio }}%</view>
				</view>
				<view class="income_block bg_c_F1EEFF">
					<view class="income_name">服务订单</view>
					<!--					<view class="income_self">本人：{{ getSelfIncome(incomeSetUpInfo.servicePromotionRatio) }}%</view>-->
					<view class="income_promoter">推广收入：{{ incomeSetUpInfo.memberServicePromotionRatio }}%</view>
				</view>
			</view>
			<!--			<view class="income_tips">注：陪宠师指接单的陪宠人员，本人指您自己。</view>-->
		</view>
		<!-- <view class="levelTwo level">
			<view class="title">
				<view class="item">
					<view class="label">服务管理</view>
					<view class="value" @click="toUrl('service')">
						<view class="valueText" v-if="listServe && listServe.length > 0">已选{{ listServe.length }}个服务</view>
						<uni-icons type="right" size="16"></uni-icons>
					</view>
				</view>
				<view class="text">
					<view class="option" v-for="(item,index) in listServe" :key="index">{{item.goods.name}}</view>
				</view>
			</view>
		</view> -->
		<view class="levelThree level">
			<view class="title">
				<view class="item" @click.stop="toUrl('album')">
					<view class="label">工作室相册</view>
					<view class="value">最多20张</view>
				</view>
				<view class="text">
					<view class="album">
						<view class="media_box" v-for="(fileItem, fileIndex) in JSON.parse(detailInfo.picJson)" :key="fileIndex">
							<view class="mediaWrap">
								<image class="media" :src="fileItem.picUrl" @tap.stop="handlePreviewImage(detailInfo.picJson, fileIndex)"></image>
								<!-- <view class="mediaText">{{fileItem.picName.indexOf('.') != -1?fileItem.picName.substring(0,fileItem.picName.indexOf('.')):fileItem.picName}}</view> -->
								<textarea class="mediaText" type="text" auto-height v-model="fileItem.picName" @blur="editPicName(fileItem)" />
							</view>
							<image class="media_delete" src="https://xjs-oss-prod.oss-cn-shenzhen.aliyuncs.com/xjs-static/icon-100.png" @tap.stop="deleteFile(fileIndex)"></image>
						</view>
					</view>
					<!-- <view @click.stop="uploadStudioPic" class="uploadBtn">
						<image src="https://xjs-oss-prod.oss-cn-shenzhen.aliyuncs.com/xjs-static/icon-97.png"></image>
					</view> -->
				</view>
			</view>
		</view>
		<image @click.stop="uploadStudioPic" class="fixedImg" src="https://xjs-oss-prod.oss-cn-shenzhen.aliyuncs.com/xjs-static/icon-159.png" mode="widthFix"></image>
	</view>
</template>

<script setup lang="ts">
import { onShow } from "@dcloudio/uni-app";
import config from "@/config/index";
import api from "@/api";
import { reactive, ref } from "vue";
import { useStudioStoreToRefs } from "@/store/useStudioStore";
import { useUserStoreToRefs } from "@/store/useUserStore";
import BigNumber from "bignumber.js";

let { identity, studio, studioBalance } = useStudioStoreToRefs();

const { userInfo, access_token } = useUserStoreToRefs();
const detailInfo = ref({});
const listServe = ref([]);
let incomeSetUpInfo = reactive({
	memberMallPromotionRatio: 0,
	memberServicePromotionRatio: 0,
	memberServiceAcceptanceRatio: 0
});
onShow(async () => {
	await getStudioInfo();
	await getStudioServe(detailInfo.value.id);
	await getIncomeSetUpInfo();
});

const getStudioInfo = async () => {
	return new Promise(async (resolve, reject) => {
		try {
			const res = await api({
				method: "get",
				url: `/mall/studio/myStudio`
			});
			useStudioStoreToRefs.studioInfo = res.data;
			detailInfo.value = res.data.studio;
			resolve(true);
		} catch (err) {
			reject(err);
		}
	});
};

const getStudioServe = async (id: string) => {
	let res: any = await api({
		method: "get",
		url: `/mall/goods/studio-goods/getGoodsByStudioId/${id}`
	});
	listServe.value = res.data;
};

const toIncomeSetUp = () => {
	uni.navigateTo({
		url: `/pages/studioManage/incomeSetUp/index?type=1&studioId=${detailInfo.value.id}`
	});
};

const getIncomeSetUpInfo = async () => {
	try {
		let params = {
			studioId: detailInfo.value.id
		};
		const { data } = await api({
			method: "get",
			url: `/mall/studio/petsitter-team/getRevenueSharing`,
			data: params
		});
		incomeSetUpInfo.memberMallPromotionRatio = new BigNumber(100).times(data?.memberMallPromotionRatio).toNumber();
		incomeSetUpInfo.memberServicePromotionRatio = new BigNumber(100).times(data?.memberServicePromotionRatio).toNumber();
		incomeSetUpInfo.memberServiceAcceptanceRatio = new BigNumber(100).times(data?.memberServiceAcceptanceRatio).toNumber();
	} catch (error) {
		console.log(error);
	}
};
const getSelfIncome = (proportion) => {
	return new BigNumber(100).minus(proportion).toNumber();
};

const uploadStudioPic = async () => {
	if (JSON.parse(detailInfo.value.picJson) && JSON.parse(detailInfo.value.picJson).length >= 20) {
		uni.showToast({
			title: "最多上传20张",
			icon: "none"
		});
		return false;
	}
	uni.chooseImage({
		count: 20,
		sizeType: ["original", "compressed"], //可以指定是原图还是压缩图，默认二者都有
		sourceType: ["camera", "album"], //从相册选择
		success: function (res) {
			// let file = res.tempFilePaths.map(v => {
			// 	return{
			// 		picName:v.substring(v.lastIndexOf('/') + 1),
			// 		picUrl:v
			// 	}
			// })
			// for(let i = 0;i<res.tempFilePaths.length;i++){
			// uploadStudioImage(res.tempFilePaths[i])
			// }
			const { tempFilePaths } = res;
			Promise.all(res.tempFilePaths.map((item) => uploadStudioImage(item)))
				.then(async (res) => {
					let arr = detailInfo.value.picJson ? [...JSON.parse(detailInfo.value.picJson), ...res] : [...res];
					// console.error(res,121221,[...JSON.parse(detailInfo.value.picJson),...res])
					if (arr.length > 20) {
						uni.showToast({
							title: "最多上传20张",
							icon: "none"
						});
						return false;
					}
					await setStudioImageApi(JSON.stringify(arr));
					await getStudioInfo();
				})
				.catch((msg) => {
					console.error(msg);
				});
		}
	});
};

const uploadStudioImage = (filePath) => {
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: config.api + "/api/mall/user/uploadAvatarPic",
			filePath: filePath,
			name: "file",
			header: {
				Authorization: access_token.value ? "Bearer " + access_token.value : "Basic bWFsbC1hcHA6bWFsbC1hcHA=",
				"x-flow-id": new Date().getTime(),
				"x-client-id": ""
			},
			success: async (uploadFileRes) => {
				// console.log(JSON.parse((uploadFileRes.data)).data,
				// filePath.substring(filePath.lastIndexOf('/') + 1))
				let obj = {
					picName: filePath.substring(filePath.lastIndexOf("/") + 1),
					picUrl: JSON.parse(uploadFileRes.data).data
				};
				resolve(obj);
			},
			fail: (error) => {
				console.error(error, 12122);
			}
		});
	});
};

const setStudioImageApi = async (url: string) => {
	const res: any = await api({
		method: "put",
		url: `/mall/studio`,
		data: {
			picJson: url,
			id: detailInfo.value.id
		}
	});
};

const handlePreviewImage = (picJson, current) => {
	let arr = JSON.parse(picJson);
	let urls = arr.map((item) => item.picUrl);
	uni.previewImage({
		urls: urls,
		current
	});
};

const deleteFile = (index) => {
	uni.showModal({
		title: "提示",
		content: "是否删除该文件",
		success: function (res) {
			if (res.confirm) {
				let arr = JSON.parse(detailInfo.value.picJson);
				arr.splice(index, 1);
				console.log(arr);
				setStudioImageApi(JSON.stringify(arr));
				setTimeout(() => {
					getStudioInfo();
				}, 500);
			} else if (res.cancel) {
				console.log("用户点击取消");
			}
		}
	});
};

const editAvatar = () => {
	uni.chooseImage({
		count: 1,
		sizeType: ["original", "compressed"], //可以指定是原图还是压缩图，默认二者都有
		sourceType: ["camera", "album"], //从相册选择
		success: function (res) {
			uploadImage(res.tempFilePaths[0]);
		}
	});
};

const uploadImage = (filePath) => {
	uni.uploadFile({
		url: config.api + "/api/mall/user/uploadAvatarPic",
		filePath: filePath,
		name: "file",
		header: {
			Authorization: access_token.value ? "Bearer " + access_token.value : "Basic bWFsbC1hcHA6bWFsbC1hcHA=",
			"x-flow-id": new Date().getTime(),
			"x-client-id": ""
		},
		success: async (uploadFileRes) => {
			await setAvatarApi(JSON.parse(uploadFileRes.data).data);
			await getStudioInfo();
		},
		fail: (error) => {
			console.error(error);
		}
	});
};

const setAvatarApi = async (url: string) => {
	const res: any = await api({
		method: "put",
		url: `/mall/studio`,
		data: {
			avatar: url,
			id: detailInfo.value.id
		}
	});
};

const editPicName = (item) => {
	if (JSON.parse(detailInfo.value.picJson) && JSON.parse(detailInfo.value.picJson).length > 0) {
		let file = JSON.parse(detailInfo.value.picJson);
		file.map((v) => {
			if (v.picUrl == item.picUrl) {
				v.picName = item.picName;
			}
		});
		setStudioImageApi(JSON.stringify(file));
		setTimeout(() => {
			getStudioInfo();
		}, 500);
	}
};

const toUrl = (type: string) => {
	if (type == "name") {
		uni.navigateTo({
			url: `/pages/studioManage/studioNameEdit/index`
		});
	} else if (type == "introduce") {
		uni.navigateTo({
			url: `/pages/studioManage/introduce/index`
		});
	} else if (type == "phone") {
		uni.navigateTo({
			url: `/pages/studioManage/studioPhone/index`
		});
	} else if (type == "address") {
		// uni.navigateTo({
		// 	url: `/pages/studioManage/address/index`
		// })
	} else if (type == "service") {
		uni.navigateTo({
			url: `/pages/workshopManagement/serviceManagement/index?studioId=${detailInfo.value.id}`
		});
	} else if (type == "album") {
		uni.navigateTo({
			url: `/pages/studio/album/index?studioId=${detailInfo.value.id}`
		});
	}
};
</script>

<style lang="scss" scoped>
.media_box {
	position: relative;
	margin-right: 12rpx;
	margin-bottom: 20rpx;

	&:last-child {
		margin-right: 0;
	}

	.media {
		width: 198rpx;
		height: 198rpx;
	}

	.mediaText {
		width: 198rpx;
		// white-space: nowrap;
		// overflow: hidden;
		// text-overflow: ellipsis;
		text-align: left;
		font-size: 24rpx;
		color: #5c5e5e;
		word-wrap: break-word;
		word-break: break-all;
		white-space: pre-wrap;
	}

	.media_delete {
		width: 32rpx;
		height: 32rpx;
		border-radius: 50%;
		position: absolute;
		right: -8rpx;
		top: -8rpx;
	}
}

.fixedImg {
	position: fixed;
	bottom: 30%;
	right: 24rpx;
	width: 136rpx;
	height: 180rpx !important;
}

.studio {
	width: 100%;
	height: 100%;
	background-color: #f9f6f6;
	padding: 32rpx 32rpx 0;
	box-sizing: border-box;
	padding-bottom: calc(constant(safe-area-inset-bottom) + 84rpx);
	padding-bottom: calc(env(safe-area-inset-bottom) + 84rpx);

	.level {
		background-color: #fff;
		padding: 0 32rpx;
		box-sizing: border-box;
		border-radius: 24rpx 24rpx 24rpx 24rpx;

		.label {
			font-weight: bold;
		}

		.album {
			// margin-top: 32rpx;
			display: flex;
			flex-wrap: wrap;
			align-items: stretch;
			// image{
			// 	width: 198rpx;
			// 	height: 198rpx;
			// }
			view {
				// text-align: center;
				// margin-top: 16rpx;
				// font-size: 24rpx;
				// color: #5C5E5E;
			}
		}
	}

	.levelTwo {
		margin: 32rpx 0;
	}

	.levelThree {
		.text {
			margin-top: 32rpx;
			display: flex;
			flex-wrap: wrap;
			position: relative;

			.option {
				display: flex;
				align-items: center;
				justify-content: center;
				width: 296rpx;
				line-height: 70rpx;
				border-radius: 8rpx 8rpx 8rpx 8rpx;
				border: 1rpx solid #cacccc;
				text-align: center;
				font-size: 30rpx;
				color: #1b2120;
				margin: 0 16rpx 24rpx 0;

				&:nth-child(2n) {
					margin-right: 0;
				}
			}

			.uploadBtn {
				width: 98rpx;
				height: 98rpx;
				border-radius: 50%;
				position: absolute;
				right: -64rpx;
				bottom: -40rpx;
				background-color: #f9f6f6;
				color: #fff;
				font-size: 26rpx;
				display: flex;
				align-items: center;
				justify-content: center;

				image {
					width: 48rpx;
					height: 48rpx;
				}
			}
		}
	}

	.item {
		font-size: 32rpx;
		color: #1a1a1a;
		display: flex;
		justify-content: space-between;
		align-items: center;
		border-bottom: 1rpx solid #e6e6e6;
		padding: 48rpx 0;
		box-sizing: border-box;

		&:last-child {
			border: none;
		}

		.value {
			width: 33%;
			display: flex;
			align-items: center;
			justify-content: flex-end;
			color: #808080;
			font-size: 28rpx;
		}

		.valueText {
			color: #808080;
			font-size: 28rpx;
			margin-bottom: 4rpx;

			.pic {
				width: 100rpx;
				height: 100rpx;
				background: linear-gradient(90deg, #ffa6bc 0%, #ffa3a3 100%);
				border-radius: 50%;
			}
		}
	}

	.title {
		border-bottom: 1rpx solid #e6e6e6;
		padding: 48rpx 0;
		box-sizing: border-box;

		&:last-child {
			border: none;
		}

		.item {
			padding: 0;
			border-bottom: none;

			.label {
				font-weight: bold;
			}

			.valueText {
				color: #1b2120;
				font-size: 26rpx;
			}
		}

		.text {
			margin-top: 40rpx;
			font-size: 30rpx;
			color: #5c5e5e;
		}
	}
}

.default_income_box {
	width: 100%;
	background: #ffffff;
	border-radius: 24rpx;
	padding: 48rpx 32rpx;
	box-sizing: border-box;
	margin: 24rpx 0;

	.default_income_title {
		display: flex;
		align-items: center;
		font-weight: bold;
		font-size: 32rpx;
		color: #1a1a1a;
		justify-content: space-between;

		.uni-icons {
		}
	}

	.default_income_block {
		display: flex;
		margin-top: 42rpx;

		.income_block {
			flex: 1;
			background: #ffe6ec;
			border-radius: 24rpx;
			margin-left: 11rpx;
			text-align: center;
			padding: 48rpx 0;
			box-sizing: border-box;

			.income_name {
				font-weight: bold;
				font-size: 30rpx;
				color: #1b2120;
			}

			.income_self {
				font-weight: 400;
				font-size: 26rpx;
				color: #5c5e5e;
				margin-top: 40rpx;
			}

			.income_promoter {
				font-weight: 400;
				font-size: 26rpx;
				color: #5c5e5e;
				margin-top: 16rpx;
			}
		}

		.income_block:first-child {
			margin-left: 0;
		}
	}

	.income_tips {
		font-weight: 400;
		font-size: 24rpx;
		color: #5c5e5e;
		margin-top: 24rpx;
	}
}

.bg_c_F1EEFF {
	background: #f1eeff !important;
}
</style>
